package handler

import (
	"github.com/gin-gonic/gin"
	"learning-pass/client/api"
	"learning-pass/client/request"
	"learning-pass/common/proto/user"
	"learning-pass/pkg"
)

func Register(c *gin.Context) {
	var data request.Register
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"data": err.Error(),
		})
		return
	}
	register, err := api.Register(c, &user.RegisterReq{
		Username: data.Username,
		Password: data.Password,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"data": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": register,
	})
}
func Login(c *gin.Context) {
	var data request.Login
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"data": err.Error(),
		})
		return
	}
	login, err := api.Login(c, &user.LoginReq{
		Username: data.Username,
		Password: data.Password,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"data": err.Error(),
		})
		return
	}
	claims := pkg.CustomClaims{ID: uint(login.Greet)}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"data": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": token,
	})
}
func AddUserStudyPlan(c *gin.Context) {
	var data request.AddUserStudyPlan
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"data": err.Error(),
		})
		return
	}
	userId := c.GetUint("userId")
	plan, err := api.AddUserStudyPlan(c, &user.AddUserStudyPlanReq{
		UserId:    int64(userId),
		Course:    data.Course,
		StartTime: data.StartTime,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"data": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 1001,
		"data": plan,
	})
}
func DelUserStudyPlan(c *gin.Context) {
	var data request.DelUserStudyPlan
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"data": err.Error(),
		})
		return
	}
	userId := c.GetUint("userId")
	plan, err := api.DelUserStudyPlan(c, &user.DelUserStudyPlanReq{
		UserId:      int64(userId),
		StudyPlanId: data.StudyPlanId,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"data": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 1001,
		"data": plan,
	})
}
